package com.wanpinghui.wphlibrary.model.base.pay;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.google.gson.reflect.TypeToken;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.wanpinghui.wphlibrary.WPHLibrary;
import com.wanpinghui.wphlibrary.common.IWPHApi;
import com.wanpinghui.wphlibrary.common.dialog.LoadingDialog;
import com.yunshl.yunshllibrary.storage.LogManager;
import com.yunshl.yunshllibrary.utils.LogUtils;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit.Network;
import retrofit.callback.YRequestCallback;
import retrofit.callback.YunShlAction;
import retrofit.callback.YunShlResult;
import retrofit.utils.ParamsAndResultUtil;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/***
 * 功能描述:支付相关管理器
 * 作者:qiujialiu
 * 时间:2017/7/14
 ***/

public final class PayManager {
    private static final int GET_ALI_RESULT = 111;
    private static final int GET_WEIXIN_RESULT = 112;
    private static final String TAG = "PayManager";
    private static PayManager instance;
    private long set_id;
    private int bidPoint;
    private List<PayResultListener> listeners;

    private PayManager(){}


    static class PayManagerHolder{
        public static final PayManager INSTANCE = new PayManager();
    }

    public static PayManager getInstance() {
        return PayManagerHolder.INSTANCE;
    }


    /**
     * 移除支付结果回调
     * @param listener
     */
    public void removePayResultListener(PayResultListener listener) {
        if (listeners != null) {
            listeners.remove(listener);
        }
    }

    /**
     * 设置支付结果回调
     * @param listener
     */
    public void addPayResultListener(PayResultListener listener) {
        if (listener == null) {
            return;
        }
        if (listeners == null) {
            listeners = new ArrayList<>();
        }
        listeners.clear();
        listeners.add(listener);
    }

    public interface PayResultListener {
        void paySuccess(long setId, int bidPoint);
        void payFail(int code, String message);
    }

    /**
     * 支付成功通知
     */
    public void paySuccess() {
        if (listeners != null) {
            for (PayResultListener listener : listeners) {
                listener.paySuccess(set_id, bidPoint);
            }
        }
    }


    /**
     * 支付失败通知
     * @param code
     * @param message
     */
    public void payFail(int code , String message) {
        if (listeners != null) {
            for (PayResultListener listener : listeners) {
                listener.payFail(code, message);
            }
        }
    }


    /**
     * 微信支付
     * @param setId 套餐id
     * @param callback
     */
    public void payByWechat(final long setId, final YRequestCallback callback) {
        if (setId == 0) {
            LogManager.getInstance().w("PayManager","构建微信支付参数,构建失败，套餐id为0");
            if (callback != null) {
                callback.onFailed(0, "套餐id不能为0");
            }
            return;
        }
        LogManager.getInstance().w("PayManager","开始构建微信支付参数："+setId);
        this.set_id = setId;
        Map map = new HashMap();
        map.put("set_id", setId);
        Network.getApi(IWPHApi.class)
                .buildWXPayParams(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<GetWXPayResult>>() {
                    @Override
                    public void call(YunShlResult<GetWXPayResult> result) {
                        LoadingDialog.dismissDialog();
                        if (result.status==200) {
                            LogManager.getInstance().w("PayManager","构建微信支付参数成功:"+result.body.getWxpay().toString());
                            weiXinPay(result.body.getWxpay().getPartnerid(), result.body.getWxpay().getPrepayid(), result.body.getWxpay().getNoncestr(),result.body.getWxpay().getTimestamp() , result.body.getWxpay().getSign(), callback);
                        }else {
                            LogManager.getInstance().w("PayManager","构建微信支付参数失败:"+result.msg);
                            if (callback != null) {
                                callback.onFailed(0, result.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback,"构建微信支付参数"));
    }


    /**
     * 微信支付
     * @param bidPoint 套餐id
     * @param callback
     */
    public void payDiscountByWechat(final int bidPoint, final YRequestCallback callback) {
        if (bidPoint == 0) {
            LogManager.getInstance().w("PayManager","构建微信支付参数,构建失败，汇币数量为0");
            if (callback != null) {
                callback.onFailed(0, "汇币数量不能为0");
            }
            return;
        }
        LogManager.getInstance().w("PayManager","开始构建微信支付参数，汇币数："+bidPoint);
        this.bidPoint = bidPoint;
        Map map = new HashMap();
        map.put("bid_point", bidPoint);
        Network.getApi(IWPHApi.class)
                .buildWXPayParams2(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<YunShlResult<GetWXPayResult>>() {
                    @Override
                    public void call(YunShlResult<GetWXPayResult> result) {
                        LoadingDialog.dismissDialog();
                        if (result.status==200) {
                            LogManager.getInstance().w("PayManager","构建微信支付参数成功:"+result.body.getWxpay().toString());
                            weiXinPay(result.body.getWxpay().getPartnerid(), result.body.getWxpay().getPrepayid(), result.body.getWxpay().getNoncestr(),result.body.getWxpay().getTimestamp() , result.body.getWxpay().getSign(), callback);
                        }else {
                            LogManager.getInstance().w("PayManager","构建微信支付参数失败:"+result.msg);
                            if (callback != null) {
                                callback.onFailed(0, result.msg);
                            }
                        }
                    }
                },new YunShlAction<Throwable>(callback,"构建微信支付参数"));
    }


    /**
     *
     * @param partnerid appid
     * @param prepayid 会话id
     * @param noncestr 随机串
     * @param sign 签名
     */
    private void weiXinPay(String partnerid, String prepayid, String noncestr, String timeStamp, String sign, YRequestCallback result){
        LogManager.getInstance().w("PayManager","调起微信支付");
        PayReq req = new PayReq();
        req.appId = WPHLibrary.getLibrary().getWeChatAppid();
        LogUtils.w("微信支付appid:"+req.appId);
        req.partnerId = partnerid;
        req.prepayId = prepayid;
        req.packageValue = "Sign=WXPay";
        req.nonceStr = noncestr;
        req.timeStamp = timeStamp;
        req.sign = sign;
        boolean success = WPHLibrary.getLibrary().getWeChat().sendReq(req);
        if (!success) {
            LogManager.getInstance().w("PayManager","调起微信支付,调起失败");
            if (result != null) {
                result.onFailed(0, "调起微信支付失败");
            }
        }
    }

}
